package com.ProdigiousAT;


import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by orlandocampos on 11/18/14.
 */
public class DataDrivenFramework2 {
    int xRows,  xCols, iWait;
    private static WebDriver wd;

    @Before
    public void setUp(){
        wd = new FirefoxDriver();
        iWait = 2000;
    }

    @Test
    public void myMainTest() throws Exception{
        //Local Variables  to store the TestData
        String siteURL, SearchTerm, SearchResult, vExecute, oSearchResults;


        //Read each set of test data from the excel
        //Declare de XL file path
        String xlPath = "C:/Users/Worker/Desktop/SecondEvaluation.xls";
        // "Sheet1" is the tab name in the excel file
        String[][] myXL = readXL(xlPath, "Sheet1");

        //See what is received from the XL file

        for (int i=0; i<xRows; i++){
            for(int j=0; j<xCols; j++ ){
             System.out.println(myXL[i][j]+"");
            }
            System.out.println("------------");
        }
/*
        //Take values form eah row in 2D local array "myXL" and load them into local variables
        for(int k=1; k<xRows; k++){
            //Execute the Test if "Y"
            vExecute = myXL[k][3];
            if(vExecute.equals("Y")){
                siteURL = myXL[k][0];
                SearchTerm = myXL[k][1];
                SearchResult = myXL[k][2];

                //Execute test
                wd.get(siteURL);
                wd.findElement(By.xpath("//input[@id='masthead-search-term']")).sendKeys(SearchTerm);

                wd.findElement(By.xpath("//button[@id='search-btn']")).click();
                Thread.sleep(iWait);

                oSearchResults = wd.findElement(By.cssSelector(".num-results.first-focus")).getText();
                System.out.println("Your search result is: " + oSearchResults+"\n");

                //Write column "Obtained Output"
                myXL[k][5] = oSearchResults;
                //Validate if the test passed or failed
                if(oSearchResults.equals(SearchResult)) {
                    //Write column Results
                    myXL[k][4] = "Passed!";
                    System.out.print("Test Passed!\n");
                }else {
                    //Write column Results
                    myXL[k][4] = "Failed";
                    System.out.print("Test Failed!\n");
                }
            }else{
                System.out.println("The row: "+ k + " is skipped!");
            }
        }
        writeXL("C:/Users/Worker/Desktop/Results.xls", "Results2", myXL);
        */
    }

    @AfterClass
    public static void tearDown(){
        wd.close();
        wd.quit();
    }

    //Method to read XL
    public String[][] readXL(String sPath, String iSheet) throws Exception{
        String[][] xData;

        //Create file instance
        File myxl = new File(sPath);
        //Create instance to be able to read the file
        FileInputStream myStream = new FileInputStream(myxl);
        HSSFWorkbook myWB = new HSSFWorkbook(myStream);
        //Gets the tab name where the data will be read
        HSSFSheet mySheet = myWB.getSheet(iSheet);
        //Define which is the last row
        xRows = mySheet.getLastRowNum() + 1;
        //Define which is the las column
        xCols = mySheet.getRow(0).getLastCellNum();
        //Set number of rows/columns to the array
        xData = new String[xRows][xCols];

        for(int i=0; i < xRows; i++){
            HSSFRow row = mySheet.getRow(i);
            for (int j=0; j < xCols; j++){
                HSSFCell cell = row.getCell(j);
                String value = cellToString(cell);
                xData[i][j] = value;
            }
        }
        return xData;
    }

    //Method to WriteXL
    public static void writeXL(String sPath, String iSheet, String[][] xData) throws Exception{
        File outFile = new File(sPath);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet osheet = wb.createSheet(iSheet);
        int xR_TS = xData.length;
        int xC_TS = xData[0].length;
        for (int myrow = 0; myrow < xR_TS; myrow++) {
            HSSFRow row = osheet.createRow(myrow);
            for (int mycol = 0; mycol < xC_TS; mycol++) {
                HSSFCell cell = row.createCell(mycol);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(xData[myrow][mycol]);
            }
            FileOutputStream fOut = new FileOutputStream(outFile);
            wb.write(fOut);
            fOut.flush();
            fOut.close();
        }
    }

    //Change cell type
    public static String cellToString(HSSFCell cell){
        //This method will convert an object of type excel cell to a string value
        int type = cell.getCellType();
        Object result;
        switch(type){
            case HSSFCell.CELL_TYPE_NUMERIC: //0
                result = cell.getNumericCellValue();
                break;
            case HSSFCell.CELL_TYPE_STRING: //1
                result = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_FORMULA: //2
                throw new RuntimeException("We can't evaluate formulas in Java");
            case HSSFCell.CELL_TYPE_BLANK: //3
                result = "%";
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN: //4
                result = cell.getBooleanCellValue();
                break;
            case HSSFCell.CELL_TYPE_ERROR: //5
                throw new RuntimeException("This cell has an error");
            default:
                throw new RuntimeException("We don't support this cell type: " + type);
        }
        return result.toString();
    }


}
